package com.example.base.adapter.selector

import android.util.SparseArray
import java.lang.ref.WeakReference
import java.util.ArrayList

internal class WeakHolderTracker {
    private val mHoldersByPosition =
        SparseArray<WeakReference<ISelectableHolder?>>()

    fun getHolder(position: Int): ISelectableHolder? {
        val holderRef =
            mHoldersByPosition[position] ?: return null
        val holder = holderRef.get()
        if (holder == null || holder.getPosition() != position) {
            mHoldersByPosition.remove(position)
            return null
        }
        return holder
    }

    fun bindHolder(holder: ISelectableHolder?, position: Int) {
        mHoldersByPosition.put(position, WeakReference(holder))
    }

    val trackedHolders: List<ISelectableHolder>
        get() {
            val holders: MutableList<ISelectableHolder> =
                ArrayList()
            for (i in 0 until mHoldersByPosition.size()) {
                val key = mHoldersByPosition.keyAt(i)
                val holder = getHolder(key)
                if (holder != null) {
                    holders.add(holder)
                }
            }
            return holders
        }
}